package com.qk.management.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.management.util.JwtUtils;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 16778
 * @date 2025/10/7 11:55
 * @description
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    public final static  Integer USER_STATUS_NORMAL = 1;
    public final static  Integer USER_STATUS_UNNORMAL = 0;

    @Override
    public PageResult<User> getUsers(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPage(),userDTO.getPageSize());
        List<User> list = userMapper.page(userDTO.getName(),userDTO.getStatus(),userDTO.getPhone(),userDTO.getDeptId());
        Page<User> pages = (Page<User>) list;
        return PageResult.<User>builder()
                .total(pages.getTotal())
                .rows(pages.getResult())
                .build();
    }

    @Override
    public void delete(List<Integer> ids) {
        userMapper.delete(ids);
    }

    @Override
    public void insert(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex((user.getUsername()+"123").getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findALl();
    }

    @Override
    public List<User> selectByRoleLabel(String roleLabel) {
        return userMapper.selectByRoleLabel(roleLabel);
    }

    @Override
    public List<User> selectByDeptId(Integer deptId) {
        return userMapper.selectByDeptId(deptId);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        boolean hasNull = BeanUtil.hasNullField(dto);
        if(hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbUser = userMapper.selectByUsername(dto.getUsername());

        if(Objects.isNull(dbUser)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }

        if(ObjectUtil.equals(dbUser.getStatus(),USER_STATUS_UNNORMAL)){
            CommonException.throwCommonException(ParamEnum.LOGIN_STATUS_ERROR);
        }

        String encodedPassword = dbUser.getPassword();
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        boolean isChecked = ObjectUtil.equals(userPassword,encodedPassword);
        if(!isChecked){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        Role role = roleMapper.selectById(dbUser.getRoleId());
        UserLoginVO vo = new UserLoginVO();
        vo.setId(dbUser.getId());
        vo.setName(dbUser.getName());
        vo.setImage(dbUser.getImage());
        vo.setRoleLabel(role.getLabel());
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",dbUser.getId());
        claims.put("username",dbUser.getUsername());
        vo.setToken(JwtUtils.generateToken(claims));
        return vo;
    }
}
